package org.example.env_boot.controller;

import org.example.env_boot.dto.ApiResponse;
import org.example.env_boot.entity.AQI;
import org.example.env_boot.entity.GridCity;
import org.example.env_boot.entity.GridProvince;
import org.example.env_boot.repository.AQIRepository;
import org.example.env_boot.repository.GridCityRepository;
import org.example.env_boot.repository.GridProvinceRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 公共数据查询控制器
 */
@RestController
@RequestMapping("/public")
@CrossOrigin(origins = "*")
public class PublicController {
    
    private final GridProvinceRepository provinceRepository;
    private final GridCityRepository cityRepository;
    private final AQIRepository aqiRepository;
    
    public PublicController(GridProvinceRepository provinceRepository, 
                           GridCityRepository cityRepository,
                           AQIRepository aqiRepository) {
        this.provinceRepository = provinceRepository;
        this.cityRepository = cityRepository;
        this.aqiRepository = aqiRepository;
    }
    
    /**
     * 获取所有省份信息
     */
    @GetMapping("/provinces")
    public ApiResponse<List<GridProvince>> getAllProvinces() {
        List<GridProvince> provinces = provinceRepository.findAllByOrderByProvinceNameAsc();
        return ApiResponse.success("获取省份信息成功", provinces);
    }
    
    /**
     * 根据省份ID获取城市列表
     */
    @GetMapping("/cities/{provinceId}")
    public ApiResponse<List<GridCity>> getCitiesByProvince(@PathVariable Integer provinceId) {
        List<GridCity> cities = cityRepository.findByProvinceIdOrderByCityNameAsc(provinceId);
        return ApiResponse.success("获取城市信息成功", cities);
    }
    
    /**
     * 获取所有城市信息
     */
    @GetMapping("/cities")
    public ApiResponse<List<GridCity>> getAllCities() {
        List<GridCity> cities = cityRepository.findAllByOrderByCityNameAsc();
        return ApiResponse.success("获取城市信息成功", cities);
    }
    
    /**
     * 获取所有AQI级别信息
     */
    @GetMapping("/aqi-levels")
    public ApiResponse<List<AQI>> getAllAQILevels() {
        List<AQI> aqiLevels = aqiRepository.findAllByOrderByAqiIdAsc();
        return ApiResponse.success("获取AQI级别信息成功", aqiLevels);
    }
    
    /**
     * 根据浓度值判断AQI级别
     */
    @GetMapping("/aqi-level")
    public ApiResponse<AQI> getAQILevel(@RequestParam Integer so2Value,
                                       @RequestParam Integer coValue,
                                       @RequestParam Integer spmValue) {
        return aqiRepository.findAQIByValues(so2Value, coValue, spmValue)
                .map(aqi -> ApiResponse.success("AQI级别判断成功", aqi))
                .orElse(ApiResponse.error("无法判断AQI级别，请检查输入参数"));
    }
    
    /**
     * 系统健康检查
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("系统运行正常");
    }
} 